// SuperInt.cpp: implementation of the CSuperInt class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "SuperInt.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CSuperInt::CSuperInt(DWORD carry)
{
	r = (ElemType *)malloc(LEN);
	lenr = 0;
	m_carry=carry;
}

CSuperInt::~CSuperInt()
{

	if (this->r)
		free(this->r);
}

void CSuperInt::Add(ElemType *a, ElemType *b)
{
	lena = strlen(a);
	lenb = strlen(b);
	len_Overall = lena > lenb ? lena : lenb;
	if (len_Overall > LEN)
	{
		printf("The result overflow!\n");
		return;
	}
	lenr = 0;

	memset(r, 0, LEN);

	for (i = 0; i < len_Overall; i++)
	{
		if (i < lena)
		{
			r[lenr] += a[lena - i - 1] - '0';
		}

		if (i < lenb)
		{
			r[lenr] += b[lenb - i - 1] - '0';
		}
                                                                                                                                                                                                                                                           
		if (r[lenr] >= m_carry)
		{
			r[lenr + 1] = 1;
		}

		r[lenr] %= m_carry;

		lenr++;
	}

	if (r[lenr] > 0)
	{
		lenr++;
	}

	SwapInt();
}

void CSuperInt::Result()
{
	char *buff;
	buff=(char*)malloc(lenr+1);
	memset(buff,0,lenr+1);
	if (lenr == 0)
	{
		return;
	}

	// r为倒序存放(低位在前，高位在后),对其进行倒序输出
	for (i = 0; i < lenr; i++)
	{
		sprintf(buff,"%s%X",buff,r[i]);
 	}
	printf("%s",buff);
	printf("\nThe result contains %d digits.\n", lenr);

	FILE *f = fopen("D:\\result.txt", "wb");
	fwrite(buff, lenr+1, 1, f);
	fclose(f);
}

void CSuperInt::Mult(ElemType *a, ElemType *b)
{
	lena = strlen(a);
	lenb = strlen(b);
	lenr = lena + lenb;

	if (lenr > LEN)
	{
		printf("The result is overflow!\n");
		return;
	}

	for (i = 0; i < lena; i++)
	{
		a[i] -= '0';
	}

	for (i = 0; i < lenb; i++)
	{
		b[i] -= '0';
	}

	memset(r, 0, LEN);
	for (i = 0; i < lena; i++)
	{
		for (j = 0; j < lenb; j++)
		{
			r[i + j] += a[lena - 1 - i] * b[lenb - 1 - j];

			if (r[i + j] >= 10)
			{
				r[i + j + 1] += r[i + j] / m_carry;
				r[i + j] %= m_carry;
			}
		}
	}

	if (r[lenr - 1] < 1)
	{
		lenr--;
	}

	SwapInt();
}

void CSuperInt::SwapInt()
{
	ElemType t;
	for (i = 0; i < lenr / 2; i++)
	{
		t = r[i];
		r[i] = r[lenr - 1 - i];
		r[lenr - 1 - i] = t;
	}
}

DWORD CSuperInt::Transfor(DWORD n)
{
	DWORD t=n;
	char *buf;
	buf=(char*)malloc(255);

	return t;
}
